package com.fs.core.security.util;

import com.fs.core.security.config.DBConfig;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * 解密帮助类
 * @author ghz
 *
 */
public class DecryptionHelper implements SecurityConstant {
	
	
	/** 日志对象 */
	public static Logger log = LoggerFactory.getLogger(DecryptionHelper.class);
	

	/**
	 * 获取解密数据
	 * @param sourceData 待解密数据
	 * @param rsaKey rsaKey
	 * @return
	 * @throws Exception
	 */
	public static String getDecryptData(String sourceData,String rsaKey) throws Exception {
		String allData = null;
		/* 分别对sm4方式以及sm2方式进行解密 */
//		String data = params.get(SSL_DATA);// 数据域
		ApplicationContext context = SpringUtil.getApplicationContext();
		DBConfig dBConfig = context.getBean(DBConfig.class);// 注意是Service，不是ServiceImpl
		String crypttype = dBConfig.getCryptType();//加密类型
		if (SecurityConstant.CRYPTTYPE_SM2.equals(crypttype)) {
			String cipherMode = dBConfig.getCipherMode();// 加密模式
			allData = new String(
					SM2Utils.decrypt(Util.hexToByte(SM2Utils.DEFAULT_PRIK), Util.hexToByte(sourceData), cipherMode));
		} 
		else {
//			String key = params.get(SSL_KEY);// rsa密钥
			String _key = getKey(rsaKey);
			SM4MatchJS sm4 = new SM4MatchJS();
			try {
				allData = sm4.decode(sourceData, _key);
			} catch (Exception e) {
				log.error("sm4解密出现异常", e);
				throw e;
			}
		}
		return allData;
	}
	
	
	/**
	 * @Title: getKey @Description: 取得AES的key @param @return String @throws
	 */
	public static String getKey(String value) {
		try {
			return new RSAUtils().decrypttoStr(value);
		} catch (Exception e) {
			throw new RuntimeException("数据解密出现异常", e);
		}
	}
	
	/**
	 * @Title: validate @Description: 校验数据完整性函数，进行密文解密+MD5校验 @param @return
	 *         boolean @throws
	 */
	public static boolean validate(String data, String md5) {

		byte[] md = new byte[32];
		byte[] msg1 = data.getBytes();
		SM3Digest sm3 = new SM3Digest();
		sm3.update(msg1, 0, msg1.length);
		sm3.doFinal(md, 0);
		String sm3Data = new String(Hex.encode(md));

		// 校验字符串完整性和正确性
		if ((sm3Data.toUpperCase().trim()).equals(md5.toUpperCase().trim())) {
			return true;
		} else {
			return false;
		}
	}

}
